/**
 * Created by hiibook on 2017/6/16.
 */
var wechatMsgConstruct = require('./wechatMsgConstruct');
var config = require('../config/config');
var crypto = require('crypto');
module.exports = function (req, res, next) {
    console.log('生成礼品码');
    if (req.wechatMsg.MsgType == "text" || req.wechatUserInfo.is_manager == 1) {
        switch (true) {
            case /生成礼品码-[0-9]{1,3}-[0-9]{1,3}/.test(req.wechatMsg.Content):
            case /SCLPM-[0-9]{1,3}-[0-9]{1,3}/.test(req.wechatMsg.Content):
                console.log('接受命令');
                GenerategiftCode(req, res, next);
                break;
            default:
                next();
                break;
        }
    } else {
        next()
    }
    function GenerategiftCode(req, res, next) {
        console.log("生成礼品码");
        var quantity = code.split('-')[1];//礼品码创建数量
        var flow = code.split('-')[2];//礼品码流量
        var codeArray = [];
        for (var i = 0; i < quantity; i++) {
            var encrypted = cipher('aes-256-cbc', config.giftCodeKey, req.wechatUserInfo.id + "-" + flow);
            console.log('生产一个邀请码');
            codeArray.push(encrypted)
        }
        codeArray.forEach(saveCode(item));
        // var chat = {
        //     Type: "text",
        //     Content: "邀请码" + codeArray
        // };
        // // 最后一步需要信息,并关闭数据库连接
        // req.mysqlConnection.end();
        // res.send(wechatMsgConstruct(req.wechatMsg, chat));

    }

    function saveCode(item, req, res, flow) {
        console.log("保存一条邀请码" + item);
        var query = req.mysqlConnection.query("INSERT INTO `" + config.mysql.database + "`.`ss_gift_code` (`code`, `from`, `data`, `type`) VALUES ('" + item + "', '" + req.wechatUserInfo.id + "', '" + flow + "', 'flow')");//炒作数据库
        query
            .on('error', function (err) {
                console.log('数据库连接失败', err)
            })
            .on('result', function (row) {
                console.log("成功插入一条" + item)
            })
            .on('end', function () {
            })
    }

    //加密算法
    function cipher(algorithm, key, buf) {
        var encrypted = "";
        var cip = crypto.createCipher(algorithm, key);
        encrypted += cip.update(buf, 'binary', 'hex');
        encrypted += cip.final('hex');
        return encrypted
    }

};